package com.tcxhb.job.core.utils;

import com.tcxhb.job.common.constants.enums.ScheduleTypeEnum;
import com.tcxhb.job.dao.dataobject.JobInfoDO;
import com.tcxhb.job.common.model.job.ScheduleConf;

import java.text.ParseException;
import java.util.Date;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/4
 */
public class SchedulerTimeUtils {

    /**
     * crontab表达式是否正确
     *
     * @param str
     * @return
     */
    public static boolean isValidCronExpression(String str) {
        return CronExpression.isValidExpression(str);
    }

    /**
     * 获取下一个执行时间
     *
     * @param fromTime
     * @return
     */
    public static Long nextSchedulerTime(JobInfoDO jobInfoDO, Date fromTime) {
        if (ScheduleTypeEnum.Cron.eq(jobInfoDO.getScheduleType())) {
            try {
                ScheduleConf conf = jobInfoDO.getScheduleConf();
                Date nextValidTime = new CronExpression(conf.getCron()).getNextValidTimeAfter(fromTime);
                return nextValidTime.getTime();
            } catch (ParseException e) {
                throw new RuntimeException("获取下只一个执行时间异常:" + jobInfoDO.getScheduleConf());
            }
        }
        return 0L;
    }

}
